var stompClient = null;
var id = null;
var token = null;
var BASE_URL = "";
var username = null;

$(function () {
    $("#name").focus();
    $("form").on('submit', function (e) {
        e.preventDefault();
    });
    $("#connect").click(function () {
        connect();
    });
    $("#disconnect").click(function () {
        disconnect();
    });
    $("#send").click(function () {
        sendName();
    });
    $("#sendAll").click(function () {
        sendNamesendAll();
    });
    setConnected(false);
});


function setConnected(connected) {
    if (connected) {
        $("#main-content").show();
        $("#username-page").hide();
    } else {
        $("#main-content").hide();
        $("#username-page").show();
    }

    //连接按钮
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    //提示文字
    if (connected) {
        $("#conversation").html("<span style='color:green '>Greetings websocket connected</span>");
    } else {
        $("#conversation").html("<span style='color:red '>websocket not connect</span>");

        $("#onLineUsers").html("");
        $("#countNumber").text(0);
    }
    $("#messageArea").html("");
}

function connect() {
    //输入的用户名
    username = document.querySelector('#name').value.trim();
    // 根据用户名 插入到 数据库 返回 用户id 和 token
    getUserToken(username);
    if (username) {
        var socket = new SockJS('/nmpSocketWeb');
        stompClient = Stomp.over(socket);
        console.log("获取连接之前的 token===============")
        console.log(token)
        stompClient.connect({token: token}, onConnected, onError);
    }
    event.preventDefault();
}

function onLineUsers(result) {
    var datas = JSON.parse(result.body);
    var data = datas.data;
    $("#onLineUsers").html("");
    $("#countNumber").text(data.length);
    for (var i = 0; i < data.length; i++) {
        var person_id = data[i].id;
        var person_Name = data[i].userName;
        if (person_id == id) {
            $("#onLineUsers").append(' <li class="list-group-item" style="background-color: #299955">我：' + person_Name + '</li>');
        } else {
            $("#onLineUsers").append(' <li class="list-group-item">用户：' + person_Name +
                '<input type="text" style="width: 50%;display: inline-block;margin-left:10%;"  class="form-control messageThis_' + person_id + '" placeholder="发送给 用户"' + person_Name + '/>' +
                '<button  class="btn btn-default" style="width:80px;margin-left:10%;display: inline-block" type="button" onclick="sendToAnotherUser(' + person_id + ')">send</button>'
                + '</li>');
        }
    }
}

function onConnected() {
    setConnected(true);
    stompClient.subscribe('/user/topic/greetings', function (greeting) {
        console.log("接：")
        console.log(greeting)
        onMessageReceived(greeting)
    });
    stompClient.subscribe('/topic/greetings', function (greeting) {
        console.log("接all：")
        console.log(greeting)
        onMessageReceived(greeting)
    });

    stompClient.subscribe('/topic/public', function (result) {
        console.log("所有在线用户！")
        console.log(result)
        onLineUsers(result);
    });
}

function disconnect() {
    if (stompClient != null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}

function sendName() {
    if (!stompClient) {
        alert("请点击 connect按钮 连接网络");
        return
    }
    stompClient.send(BASE_URL + "/app/test/toOne", {token: token}, JSON.stringify({
        'message': $("#message").val(),
        'id': id
    }));
}

function sendToAnotherUser(sendTo) {
    if (!stompClient) {
        alert("请点击 connect按钮 连接网络");
        return
    }
    stompClient.send(BASE_URL + "/app/test/toOne", {token: token}, JSON.stringify({
        'message': $(".messageThis_" + sendTo).val(),
        'id': sendTo,
        'from': id
    }));
}

function sendNamesendAll() {
    if (!stompClient) {
        alert("请点击 connect按钮 连接网络");
        return
    }
    stompClient.send(BASE_URL + "/app/test/testAll", {token: token}, JSON.stringify({
        'message': $("#message").val(),
        'from': id
    }));
}

function serverSend() {

    if (!stompClient) {
        alert("请点击 connect按钮 连接网络");
        return
    }
    $.get(BASE_URL + "/webSocket/sendMsg", function (result) {
        console.log("服务器推送成功！")
    });
}

function getUserToken(username) {
    $.ajax({
        type: "GET",
        url: BASE_URL + "/webSocket/token?username=" + username,
        async: false,
        success: function (result) {
            token = result.token;
            id = result.userId;
            console.log("====================获取token  he id=========================")
            console.log(token)
            console.log(id)
            $("#randomLocal").html("【" + username + "】当前用户唯一标识:" + id)
            $("#tokenLocal").html("JWT token：:" + token)
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // 状态码
            console.log(XMLHttpRequest.status);
            // 状态
            console.log(XMLHttpRequest.readyState);
            // 错误信息
            console.log(textStatus);
            onError("错误码：[" + XMLHttpRequest.status + "] 状态：[" + XMLHttpRequest.readyState + "] 错误信息：[" + textStatus + "]")
        }
    });
}

/**************************index js逻辑*********************/
var usernamePage = document.querySelector('#username-page');
var chatPage = document.querySelector('#chat-page');
var usernameForm = document.querySelector('#usernameForm');
var messageForm = document.querySelector('#messageForm');
var messageInput = document.querySelector('#message');
var messageArea = document.querySelector('#messageArea');
var connectingElement = document.querySelector('.connecting');

var colors = [
    '#2196F3', '#32c787', '#00BCD4', '#ff5652',
    '#ffc107', '#ff85af', '#FF9800', '#39bbb0'
];


usernameForm.addEventListener('submit', connect, true)


function onError(error) {
    setConnected(false);
    if (!error) {
        error = "Could not connect to WebSocket server. <br/> Please refresh this page to try again!";
    }
    $("#conversation").html("<span style='color:red '>" + error + "</span>");
    $("#conversationForm").html("<span style='color:red '>" + error + "</span>");

}

function onMessageReceived(payload) {
    var message = JSON.parse(payload.body);
    var messageElement = document.createElement('li');

    if (message.type === 'JOIN') {
        messageElement.classList.add('event-message');
        message.content = message.sender + ' joined!';
    } else if (message.type === 'LEAVE') {
        messageElement.classList.add('event-message');
        message.content = message.sender + ' left!';
    } else {
        messageElement.classList.add('chat-message');
        var avatarElement = document.createElement('i');
        var avatarText = document.createTextNode(message.sender);
        avatarElement.appendChild(avatarText);
        avatarElement.style['background-color'] = getAvatarColor(message.sender);
        if (message.sender == username) {
            avatarElement.style['right'] = "10px";
            messageElement.style['text-align'] = "right";
        } else {
            avatarElement.style['left'] = "10px";

        }
        messageElement.appendChild(avatarElement);

        var usernameElement = document.createElement('span');
        var usernameText = document.createTextNode(message.sender);
        usernameElement.appendChild(usernameText);
        messageElement.appendChild(usernameElement);
    }

    var textElement = document.createElement('p');
    var messageText = document.createTextNode(message.content);
    textElement.appendChild(messageText);

    messageElement.appendChild(textElement);

    messageArea.appendChild(messageElement);
    messageArea.scrollTop = messageArea.scrollHeight;
}

function getAvatarColor(messageSender) {
    var hash = 0;
    for (var i = 0; i < messageSender.length; i++) {
        hash = 31 * hash + messageSender.charCodeAt(i);
    }
    var index = Math.abs(hash % colors.length);
    return colors[index];
}
